package com.os.osframe.scaffold.create;

import com.os.osframe.scaffold.util.Native2Ascii;
import com.os.osframe.scaffold.domain.ScaffoldXmlTable;
import com.os.osframe.scaffold.util.PropertyConfigurerLoader;
import com.os.osframe.scaffold.util.SpringUtils;
import com.os.osframe.util.DateUtil;
import com.os.osframe.util.StringUtil;

import javax.annotation.Resource;
import java.io.*;
import java.util.Date;

/**
 * Created by wangdc on 2015-4-27.
 */
public class BaseCreate {
    protected String[] replaceStrings = new String[10];
    protected String[] targetStrings = new String[10];
    //protected String domain = "";
    protected String author ;
    protected String i18nProp = "properties";//属性文件，不覆盖，结束后编码
    protected ScaffoldXmlTable scaffoldXmlTable;


    protected PropertyConfigurerLoader propertyConfigurer;
    public PropertyConfigurerLoader getPropertyConfigurer(){
        if(propertyConfigurer==null){
            propertyConfigurer= (PropertyConfigurerLoader) SpringUtils.getBean("propertyConfigurer");
        }
        return propertyConfigurer;
    }
    public BaseCreate(){

    }
    public BaseCreate(ScaffoldXmlTable scaffoldXmlTable){
        this.scaffoldXmlTable=scaffoldXmlTable;
    }
    /**
     * 待替换变量
     * @param packages 模块包路径
     */
    protected void stringDeal(String packages){
        replaceStrings[0]="${packages}";
        replaceStrings[1]="${domainPath}";
        replaceStrings[2]="${domain}";
        replaceStrings[3]="${author}";
        replaceStrings[4]="${time}";
        replaceStrings[5]="${info}";
        replaceStrings[6]="${domainVar}";
        replaceStrings[7]="${table}";
        replaceStrings[8]="${packageSimple}";
        replaceStrings[9]="${packagePath}";


        //获取域模型信息

        //获取包简称
        String packagesSimple=null;
        String[] packagesSimpleArr=packages.split("\\.");

        for(int i=0;i<packagesSimpleArr.length;i++){
            if(StringUtil.isNull(packagesSimple)){
                packagesSimple=packagesSimpleArr[i];
            }else{
                packagesSimple+=packagesSimpleArr[i].substring(0, 1).toUpperCase()+packagesSimpleArr[i].substring(1);
            }
        }
        targetStrings[0]=packages;
        targetStrings[8]=packagesSimple;
        targetStrings[9]=packages.replaceAll("\\.","/");
        if(author==null){

            author = (String) getPropertyConfigurer().getProperty("osframe.auto.author");//获取属性配置的服务器路径
        }
        targetStrings[3]=author;
        targetStrings[4]= DateUtil.convertDate2String(DateUtil.DATETIME_FORMAT, new Date());
        if(scaffoldXmlTable!=null){//当跟包相关的时候 不 能使用 ${domainPath} ${domain} ${info} ${domainVar} ${table}
            targetStrings[1]="/"+packages.replaceAll("\\.","/")+"/"+scaffoldXmlTable.getJavaName();
            targetStrings[2]=scaffoldXmlTable.getDomain();
            targetStrings[5]=scaffoldXmlTable.getTableInfo();
            targetStrings[6]=scaffoldXmlTable.getDomain().substring(0, 1).toLowerCase()+scaffoldXmlTable.getDomain().substring(1);
            targetStrings[7]=scaffoldXmlTable.getTableName();
        }


    }
    /**
     *  生成文件
     * @param tempPath
     * @param targetPath
     * @throws Exception
     */
    public void createFile(String tempPath,String targetPath)throws  Exception{
        System.out.println("正在生成文件：" + tempPath + " -> " + targetPath);
        File tempFile = new File(tempPath);
        File targetFile = new File(targetPath);
        if (tempFile.isDirectory()) {
            Boolean bool=targetFile.mkdirs();//直接进入到多层子集导致没有目录而创建失败
            System.out.println("创建文档："+bool);
            String[] files = tempFile.list();
            if (files != null) {
                for (int i = 0; i < files.length; i++) {
                    if (files[i].startsWith("."))
                        continue;
                    createFile(tempPath + "/" + files[i], targetPath + "/"+ replaceText(files[i]));
                }
            }
        } else {
            StringBuffer sb = new StringBuffer();
            BufferedReader input = new BufferedReader(new InputStreamReader(
                    new FileInputStream(tempFile), "UTF-8"));
            for (String s = input.readLine(); s != null; s = input.readLine()){
                sb.append(s + "\r\n");
            }

            input.close();
            BufferedWriter output = null;
            String writeStr=null;
            if(targetFile.exists() && i18nProp.equals(targetPath.substring(targetPath.lastIndexOf(".")+1))){//当文件存在
                output = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(targetFile,true), "UTF-8"));
                writeStr="\r\n"+replaceText(sb.toString());
                writeStr=replaceCode(writeStr);
                writeStr= Native2Ascii.native2ascii(writeStr);//转换中文编码
            }else{

                targetFile.createNewFile();
                output = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(targetFile), "UTF-8"));
                writeStr=replaceText(sb.toString());
                writeStr=replaceCode(writeStr);
            }

            output.write(writeStr);
            output.close();
        }
    }
    protected String replaceStr(String srcText, String fromStr, String toStr) {
        if (srcText == null || fromStr==null)
            return null;
        StringBuffer rtnVal = new StringBuffer();
        String rightText = srcText;
        for (int i = rightText.indexOf(fromStr); i > -1; i = rightText
                .indexOf(fromStr)) {
            rtnVal.append(rightText.substring(0, i));
            rtnVal.append(toStr);
            rightText = rightText.substring(i + fromStr.length());
        }
        rtnVal.append(rightText);
        return rtnVal.toString();
    }

    /**
     * 循环替换预置的替换文本
     * @param srcText
     * @return
     */
    protected String replaceText(String srcText) {
        String rtnVal = srcText;
        for (int i = 0; i < replaceStrings.length; i++) {
            if(rtnVal==null || "".equals(rtnVal) || replaceStrings[i]==null || "".equals(replaceStrings[i])){
                continue;
            }
            rtnVal = replaceStr(rtnVal, replaceStrings[i], targetStrings[i]);
        }
        return rtnVal;
    }

    /**
     * 替换代码，用于子类自行实现
     * @param srcText
     * @return
     */
    protected String replaceCode(String srcText)throws Exception {
        return srcText;
    }

}
